#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
应用程序框架分析器 - GUI工具函数
"""

import os
import sys
import tkinter as tk
import logging
import yaml
from pathlib import Path

logger = logging.getLogger("GUIUtils")

def init_drag_and_drop():
    """初始化拖放支持"""
    try:
        # 尝试导入tkinterdnd2
        import tkinterdnd2
        from tkinterdnd2 import DND_FILES
        
        # 全局定义DND_FILES，以便main_window.py可以使用
        globals()['DND_FILES'] = DND_FILES
        
        root = tkinterdnd2.TkinterDnD.Tk()
        logger.info("成功初始化tkinterdnd2拖放支持")
        return root
    except ImportError:
        # 如果没有tkinterdnd2，尝试安装它
        logger.warning("检测到缺少tkinterdnd2库，正在尝试安装...")
        try:
            import subprocess
            subprocess.check_call([sys.executable, "-m", "pip", "install", "tkinterdnd2"])
            import tkinterdnd2
            from tkinterdnd2 import DND_FILES
            
            # 全局定义DND_FILES，以便main_window.py可以使用
            globals()['DND_FILES'] = DND_FILES
            
            root = tkinterdnd2.TkinterDnD.Tk()
            logger.info("成功安装并初始化tkinterdnd2拖放支持")
            return root
        except Exception as e:
            logger.error(f"安装tkinterdnd2失败: {e}")
            logger.warning("将使用基本界面，没有拖放功能")
            
            # 使用普通的Tk
            root = tk.Tk()
            
            # 模拟拖放接口，使程序不会崩溃
            tk.Widget.drop_target_register = lambda self, *args: None
            tk.Widget.dnd_bind = lambda self, *args: None
            return root

def load_config():
    """加载配置文件"""
    config_path = Path("config.yaml")
    
    # 默认配置
    default_config = {
        "windows": {
            "frameworks": {
                "WPF": {
                    "files": ["PresentationCore.dll", "PresentationFramework.dll"],
                    "patterns": ["System.Windows.Controls", "System.Windows.Media"]
                },
                "WinForms": {
                    "files": ["System.Windows.Forms.dll"],
                    "patterns": ["System.Windows.Forms"]
                }
            }
        },
        "android": {
            "frameworks": {
                "Flutter": {
                    "files": ["libflutter.so", "flutter_assets"],
                    "patterns": ["io.flutter", "flutter.embedding"]
                }
            }
        },
        "report": {
            "template": "default",
            "include_details": True
        }
    }
    
    # 尝试加载配置文件
    if config_path.exists():
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                user_config = yaml.safe_load(f)
                if user_config:
                    # 合并配置
                    return merge_configs(default_config, user_config)
                else:
                    return default_config
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}")
            return default_config
    else:
        # 如果配置文件不存在，创建默认配置
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                yaml.dump(default_config, f, allow_unicode=True, default_flow_style=False)
            logger.info(f"已创建默认配置文件: {config_path}")
        except Exception as e:
            logger.error(f"创建默认配置文件失败: {e}")
        
        return default_config

def merge_configs(default_config, user_config):
    """合并默认配置和用户配置"""
    if not isinstance(user_config, dict):
        return default_config
    
    result = default_config.copy()
    
    for key, value in user_config.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = merge_configs(result[key], value)
        else:
            result[key] = value
    
    return result 
